import Picdiet from "./picdiet.min"
//var Picdiet = require("./picdiet.min.js")
// console.log("Picdiet加载完成=>", Picdiet);
import JSZip from "jszip"
let [readAsText, readAsArrayBuffer, readAsDataURL] = ['readAsText', 'readAsArrayBuffer', 'readAsDataURL'].map(read => file => new Promise(resolve => {
    var reader = new FileReader();
    reader[read](file);
    reader.onload = e => {
        resolve(e.target.result)
    }
}
));
let getImageData = (file) => {
    return readAsArrayBuffer(file).then(buffer => new Uint8Array(buffer));
}
let getDataUrl = (file) => {

    return readAsDataURL(file).then(function (url) {
        return url;
    })
}
let bytesToSize = (a, b) => {
    if (0 == a)
        return "0 Bytes";
    var c = 1024
        , d = b || 2
        , e = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
        , f = Math.floor(Math.log(a) / Math.log(c));
    return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f]
}
/**
 * @description 压缩图片开始
 * @param {file} file 图片资源
 * @param {function} callback 处理后回调事件
 * @param {number} proportion 处理质量 百分比 默认75%
 * @returns {object} 返回对象聚合 newFile 压缩过后的文件 oldFile 之前文件 zipFile 压缩后再zip压缩后的文件
 * @author 一枚前端
 */
let loadImage = function (file, callback, proportion) {
    if (file.type.split("/")[1] == "png") {
        typeof callback == "function" ? callback({
            newFile: file,//新资源
            oldFile: file,//旧资源
            msg: "图片格式为PNG,未压缩,直接返回"
        }) : "";
        return;
    };
    getImageData(file).then(data => {
        var result = Picdiet(data, {
            quality: proportion || 75//处理质量 百分比
        });
        var zip = new JSZip();
        var imgfolder = zip.folder("picdiet");
        var blob = new Blob([result.data], {
            type: 'image/jpeg'
        });
        typeof callback == "function" ? callback({
            newFile: blob,//新资源
            oldFile: file,//旧资源
            zipFile: imgfolder.file(file.name, blob),
        }) : "";
    });
}
export default { getImageData, getDataUrl, bytesToSize, loadImage };
